package com.servlet;

import com.model.Personal;
import com.service.PersonalService;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/PersonalServlet")
public class PersonalServlet extends HttpServlet {
    PersonalService ps = new PersonalService();
    HttpServletRequest request;
    HttpServletResponse response;

    @SneakyThrows
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        request.setCharacterEncoding("utf-8");
        this.request = request;
        this.response = response;
        String me = request.getParameter("method");
        if (me.equals("show")) {
            this.show();
        }
        if (me.equals("toupdate")){
            this.toupdate();
        }
        if (me.equals("update")){
            this.update();
        }
    }

    private void toupdate() throws ServletException, IOException, SQLException {
        int id = Integer.parseInt(request.getParameter("id"));
        Personal personal = ps.selectById(id);
        request.setAttribute("personals",personal);
        request.getRequestDispatcher("personal/update.jsp").forward(request, response);
    }
    private void update() throws IOException {
        String mid = request.getParameter("mid");
        String realname = request.getParameter("realname");
        String sex = request.getParameter("sex");
        String city = request.getParameter("city");
        String number = request.getParameter("number");
        String telephone = request.getParameter("telephone");
        String email = request.getParameter("email");
        ps.update(mid,realname,sex,city,number,telephone,email);
        response.setContentType("text/html; charset=UTF-8");
        response.getWriter().print("<script>parent.showPersonal()</script>");
    }


    private void show() throws ServletException, IOException {
        List<Personal> personals = ps.show();
        System.out.println(personals.toString());
        request.setAttribute("personals", personals);
        request.getRequestDispatcher("personal/show.jsp").forward(request, response);
    }
}